#include <stdio.h>
#include <stdlib.h>

void printfMatrix(int n)
{
    int i,j;
    int value = 1; //初始化为X
    int rows = 0,rows_end = n-1;  //行
    int cols = 0,cols_end = n-1;  //列
    int num = (-2); //数值

    if(n <= 3 || n >=30)
    {
        printf("error\n");
        return;
    }

    char **matrix = (char **)malloc(n * sizeof(char *));    //为二维数组的指针分配内存
    for(i = 0; i < n; i++)  //为每一行分配内存
    {
        matrix[i] = (char *)malloc(n*sizeof(char));
    }

    //打印方阵的每一层
    while(rows <= rows_end && cols <= cols_end )
    {
        //打印第一行
        for(i = rows; i <= rows_end; i++)
        {
            matrix[rows][i] = (value == 1) ? 'X': (value == 2) ? 'Y' : (num % 10) +'0';
        }
        rows++;
        
        //打印第一列
        for(i = cols; i <= cols_end ; i++)
        {
            matrix[i][cols] = (value == 1) ? 'X': (value == 2) ? 'Y' :  (num%10)+ '0';
        }
        cols++;

        //打印最后一行
        for(i = rows_end; i >= rows; i--)
        {
            matrix[rows_end][i] = (value == 1) ? 'X': (value == 2) ? 'Y' : (num%10) + '0';
        }
        rows_end--;

        //打印最后一列
        for(i = cols_end; i >= cols ; i--)
        {
            matrix[i][cols_end] = (value == 1) ? 'X': (value == 2) ? 'Y' : (num%10) + '0';
        }
        cols_end--;

        value++;
        num++;
        
    }

    //输出方阵
    for(int i = 0; i < n ; i++)
    {
        for(int j = 0; j < n ; j++)
        {
            printf("%c ",matrix[i][j]);
        }
        printf("\n");
    }
    printf("\n");

    //释放内存
    for(int i = 0; i < n; i++)
        free(matrix[i]);
    
    free(matrix);
}

int main(int argc, char const *argv[])
{
    int N;
    printf("请输入N(3<N<30)的值:\n");
    scanf("%d",&N);

    printfMatrix(N);
    
    return 0;
}
